/**
 * 公共方法
 */

/** 获取系统时间日期, 返回:
 * @returns dateNum: 日期, dayStr: 星期
 */
const getNowDateStr = () => {
  const nowDate = new Date();
  const dayStrs = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

  const dateNum = nowDate.getDate();
  const dayStr = dayStrs[nowDate.getDay()];

  return {
    dateNum,
    dayStr,
  };
};

/**
 * 格式化时间戳
 * @param timer 时间戳
 * @returns
 */
const formatDateTime = (timer: number, char: string = '-') => {
  if (!timer) return;
  const time = new Date(timer);
  const hour = time.getHours();
  const yearStr = __strNumLess10AddZore(time.getFullYear());
  const mouthStr = __strNumLess10AddZore(time.getMonth() + 1);
  const dateStr = __strNumLess10AddZore(time.getDate());
  const hourStr = __strNumLess10AddZore(time.getHours());
  const minuteStr = __strNumLess10AddZore(time.getMinutes());
  const secondStr = __strNumLess10AddZore(time.getSeconds());

  return (
    yearStr + char + mouthStr + char + dateStr + ' ' + hourStr + ':' + minuteStr + ':' + secondStr
  );
};

/**
 * 文本型数字,小于10补 '0'
 * @param date
 */
const __strNumLess10AddZore = (date: number) => {
  if (date < 10) {
    return '0' + date.toString();
  }
  return date.toString();
};

export { getNowDateStr, formatDateTime };

import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';

/**
 * ele:需要导出的容器
 * pdfName：导出文件的名字
 * callback: 成功回调
 */
export function downloadPDF(ele: any, pdfName: any, callback: any, scale?: number) {
  html2canvas(ele, {
    dpi: 600,
    scale: scale ? scale : 8,
    // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
    useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    width: ele.scrollWidth,
    height: ele.scrollHeight,
  }).then((canvas) => {
    //未生成pdf的html页面高度
    var leftHeight = canvas.height;
    var a4Width = 595.28;
    var a4Height = 801.89; //（一张A4高=841.89减去20，使得上下边距空出20,pdf.addImage生成上边距（第四个参数=10）致使使得上下边距各10）
    //一页pdf显示html页面生成的canvas高度;
    var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height);
    //pdf页面偏移
    var position = 0;
    var pageData = canvas.toDataURL('image/jpeg', 1.0);
    var pdf = new JsPDF('x', 'pt', 'a4');
    var index = 1,
      canvas1 = document.createElement('canvas'),
      height;
    pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

    function createImpl(canvas) {
      if (leftHeight > 0) {
        index++;
        var checkCount = 0;
        if (leftHeight > a4HeightRef) {
          var i = position + a4HeightRef;
          for (i = position + a4HeightRef; i >= position; i--) {
            var isWrite = true;
            for (var j = 0; j < canvas.width; j++) {
              var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data;
              if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                isWrite = false;
                break;
              }
            }
            if (isWrite) {
              checkCount++;
              if (checkCount >= 10) {
                break;
              }
            } else {
              checkCount = 0;
            }
          }
          height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
          if (height <= 0) {
            height = a4HeightRef;
          }
        } else {
          height = leftHeight;
        }
        canvas1.width = canvas.width;
        canvas1.height = height;
        var ctx = canvas1.getContext('2d');
        ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);
        if (position != 0) {
          pdf.addPage();
        }
        // 在pdf.addImage(pageData, 'JPEG', 左间距，上间距，宽度，高度)设置在pdf中显示；
        pdf.addImage(
          canvas1.toDataURL('image/jpeg', 1.0),
          'JPEG',
          70,
          56,
          a4Width - 140,
          (a4Width / canvas1.width) * height - 112,
        );

        leftHeight -= height;
        position += height;
        if (leftHeight > 0) {
          setTimeout(createImpl, 500, canvas);
          callback();
        } else {
          pdf.save(pdfName);
          callback();
        }
      }
    }

    // 当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < a4HeightRef) {
      pdf.addImage(pageData, 'JPEG', 0, 50, a4Width, (a4Width / canvas.width) * leftHeight);
      pdf.save(pdfName);
      // callback();
    } else {
      try {
        pdf.deletePage(0);
        setTimeout(createImpl, 500, canvas);
      } catch (err) {
        console.log(err);
      }
    }
  });
}

//  升序
export const ObjAscend = function (parm: string) {
  return function (obj1: any, obj2: any) {
    var val1 = obj1[parm];
    var val2 = obj2[parm];
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1);
      val2 = Number(val2);
    }
    if (val1 > val2) {
      return -1;
    } else if (val1 < val2) {
      return 1;
    } else {
      return 0;
    }
  };
};
//  降序
export const ObjDescend = function (parm: string) {
  return function (obj1: any, obj2: any) {
    var val1 = obj1[parm];
    var val2 = obj2[parm];
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1);
      val2 = Number(val2);
    }
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      return 0;
    }
  };
};

export const linkDownLoad = (res: any, name: string) => {
  const link = document.createElement('a');
  let blob = new Blob([res], { type: 'application/x-compressed-tar' });
  link.style.display = 'none';
  //设置连接
  link.href = URL.createObjectURL(blob);
  link.download = name + '.tar.gz';
  document.body.appendChild(link);
  //模拟点击事件
  link.click();
  window.URL.revokeObjectURL(link.href);
};
export const getColor = (specifier: any) => {
  if (Array.isArray(specifier)) specifier = specifier.join('');
  var n = (specifier.length / 6) | 0,
    colors = new Array(n),
    i = 0;
  while (i < n) colors[i] = '#' + specifier.slice(i * 6, ++i * 6);
  return colors;
};

export const canvasMark = (domId: string) => {
  var canvas = document.getElementById(domId);

  let width = 800;
  let height = 800;
  let x = 80;
  let y = 50;

  let markWidth = 40;
  let markHeight = 2;

  let yxixs = [
    20500, 28800, 33300, 54700, 78200, 104500, 138900, 167100, 173400, 216900, 244400, 310100,
    336500, 398400, 452700, 668900, 1135000,
  ];

  var markArray = [
    {
      name: 'mark',
      data: [
        20500, 28800, 33300, 54700, 78200, 104500, 138900, 167100, 173400, 216900, 244400, 310100,
        336500, 398400, 452700, 668900, 1135000,
      ],
    },
    {
      name: '003515',
      data: [
        923651, 702622, 653724, 326988, 297222, 273431, 252056, 247082, 193016, 180215, 167406,
        145010, 115344, 110329, 45012, 20992, 20553, 6516, 1203,
      ],
    },
    {
      name: '001705',
      data: [
        923612, 702622, 653743, 326212, 296395, 273431, 252055, 247081, 193008, 180215, 167406,
        145010, 115344, 110329, 45012, 20992, 20553, 6516, 1203,
      ],
    },
    {
      name: '005889',
      data: [
        923129, 666470, 653485, 326212, 296391, 253381, 252060, 247084, 193005, 180215, 167406,
        145010, 115358, 110329, 79046, 20992, 42215, 6516, 1203,
      ],
    },
  ];

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.fillStyle = '#FFF';
    // drawing code here
    // ctx.beginPath();
    // //横坐标
    // ctx.moveTo(x, height-x);
    // ctx.lineTo(height, width -x );
    // //纵坐标
    // ctx.moveTo(x, height-x);
    // ctx.lineTo(x, y-height);
    // ctx.stroke();

    //画纵坐标
    //    ctx.fillStyle = '#00F';
    ctx.font = '14px Sans-Serif';

    ctx.textBaseline = 'Top';

    //    ctx.moveTo(x-60,y-height);
    //    ctx.fillText('0', x-20, height-x);

    let diff =
      (height - 30 - y) /
      (Math.LOG10E * Math.log(yxixs[yxixs.length - 1]) - Math.LOG10E * Math.log(yxixs[0]));

    //  console.log(diff)

    // for (let i = 0; i < yxixs.length; i++) {
    //     let tempY = height - 2 * y - (Math.LOG10E * Math.log(yxixs[i]) - Math.LOG10E * Math.log(yxixs[0])) * diff;
    //         console.log('*******'+i+'*********'+tempY)

    //         ctx.fillText(yxixs[i], x-60,tempY);
    //         ctx.moveTo(x,tempY);
    //         ctx.lineTo(x+10, tempY);

    // }
    ctx.stroke();

    ctx.fillStyle = '#FFF';
    for (let i = 0; i < markArray.length; i++) {
      let tempData = markArray[i].data.reverse();

      tempData.forEach((element) => {
        let tempY =
          height -
          2 * y -
          (Math.LOG10E * Math.log(element) - Math.LOG10E * Math.log(yxixs[0])) * diff;
        console.log(tempY);

        if (tempY < 0) {
          tempY = -tempY;
        }
        ctx.fillRect(x + 50 + i * 60, tempY, markWidth, markHeight); // x轴 y轴 宽 和 高 ,绘制“被填充”的矩形
      });
    }
    ctx.rotate(180);

    //画横坐标

    // ctx.beginPath();
    // ctx.moveTo(25, 25);
    // ctx.lineTo(105, 25);
    // ctx.lineTo(25, 105);
    // ctx.fill();

    // ctx.beginPath();
    // ctx.moveTo(125, 125);
    // ctx.lineTo(125, 45);
    // ctx.lineTo(45, 125);
    // ctx.closePath();
    // ctx.stroke();
  } else {
    // canvas-unsupported code here
  }
};
//节流
let timer_throttle: any;
export const throttle = (func: Function, wait?: number) => {
  wait = wait || 500;
  if (!timer_throttle) {
    timer_throttle = setTimeout(() => {
      func.apply(this);
      timer_throttle = null;
    }, wait);
  }
};
let timer_debounce: any;
export const debounce = (func: Function, wait?: number) => {
  wait = wait || 500;
  clearTimeout(timer_debounce);
  timer_debounce = setTimeout(() => {
    func.apply(this);
  }, wait);
};
export const formatQuery = (q: any) => {
  let query = '';
  Object.keys(q).forEach((key) => {
    if (q[key] !== '' && q[key] !== undefined) {
      query += `${key}=${q[key]}&`;
    }
  });
  return query.substring(0, query.length - 1);
};

//arr: 要去重的数组， attribute：按照对象的属性去重
export const deWeightThree = (arr: Array<any>, attribute: string) => {
  let map = new Map();
  for (let item of arr) {
    if (!map.has(item[attribute])) {
      map.set(item[attribute], item);
    }
  }
  return [...map.values()];
};

//判断两个数组是否有相同元素
export const ishasSameElement = (arr1: string[], arr2: string[]) => {
  // 使用Set数据结构来存储数组的唯一元素
  let set1 = new Set(arr1);
  let set2 = new Set(arr2);
  // 使用Intersection方法找出两个集合的交集，如果交集不为空，那么就存在共享的元素
  let commonElements = new Set([...set1].filter((x) => set2.has(x)));

  return Array.from(commonElements);
};
